<template>
  <div class="scan_record">
    <div class="tool select">
      <ToolBar :show-edit="false" :delete-disable="multipleSelection.length===0" :delete-data="deleteById"
               :show-all="false" :show-multiple="false" :show-add="false"></ToolBar>
      <div class="select" style="margin-left: 0.5rem;">
        <el-form :inline="true">
          <el-form-item label="员工姓名：">
            <el-select v-model="form.userIds" placeholder="请选择员工姓名..." size="small" value-key="userId"
                       collapse-tags filterable clearable multiple>
              <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId"
                         v-for="item in $store.state.userList">
                <span style="float: left">{{ item.userName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出勤日期：">
            <el-date-picker v-model="attendanceDate" size="small"
                            type="daterange"
                            align="left"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :default-time="['00:00:00', '23:59:59']"
                            :picker-options="pickerOptions"
                            :clearable="false"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>


            <el-button type="primary" @click="handleCurrentChange(1)" size="small">筛选</el-button>
            <el-button type="primary" @click="reSet" size="small"
                       icon="el-icon-refresh">重置
            </el-button>
            <el-button type="primary" @click="goGetData" size="small"
                       icon="el-icon-download">获取打卡数据
            </el-button>
            <el-button type="primary" @click="goGetData" size="small"
                       icon="el-icon-download">获取整个月打卡数据
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog title="打卡数据获取" :visible.sync="getDataDialogFormVisible" center>
      <el-form :model="form" label-width="8rem">
        <el-form-item label="员工姓名：">
          <el-select v-model="form.userId" placeholder="请选择员工姓名..." class="w100" size="small" value-key="userId"
                     filterable clearable>
            <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId"
                       v-for="item in $store.state.userList">
              <span style="float: left">{{ item.userName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考勤日期：">
          <el-date-picker style="width: 100%!important;" size="small"
                          v-model="attendanceDate"
                          type="daterange"
                          align="left"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd"
                          :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.delete">删除原有数据</el-checkbox>
          <el-checkbox v-model="form.checked">拉取连班加班数据</el-checkbox>
          <el-checkbox v-model="form.isDayCalculate">考勤数据计算</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="getDataDialogFormVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="getDataFromDingDing" size="small">确 定</el-button>
        <el-button type="primary" @click="getTheMonthData" size="small">获取整月数据</el-button>

      </div>
    </el-dialog>
    <el-table
        :data="tableData"
        stripe
        border
        default-expand-all
        @selection-change="handleSelectionChange"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
      <el-table-column type="selection" label="序号">
      </el-table-column>
      <el-table-column label="用户ID" prop="userId" width="180"></el-table-column>
      <el-table-column label="考勤日期" prop="workDate" min-width="80">
        <template slot-scope="scope">
          {{ scope.row.workDate|formatDateBirth }}
        </template>
      </el-table-column>
      <el-table-column label="星期">
        <template slot-scope="scope">
          {{ scope.row.workDate|formatDateDDDD }}
        </template>
      </el-table-column>

      <el-table-column label="员工姓名" prop="userName">
      </el-table-column>
      <el-table-column label="员工工号" prop="jobNo">
      </el-table-column>
      <el-table-column label="数据来源" prop="sourceType"></el-table-column>
      <el-table-column label="基准打卡时间" width="150">
        <template slot-scope="scope">
          {{ scope.row.baseCheckTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="员工打卡时间" prop="workDate" width="150">
        <template slot-scope="scope">
          {{ scope.row.userCheckTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.createTime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="审批单" prop="procinstId" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="考勤结果" prop="timeResult">

      </el-table-column>
      <el-table-column label="操作" min-width="120">
        <template slot-scope="scope">

          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[12, 24, 36, 48]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";
import moment from "moment";

export default {
  name: "AttendanceResultList",
  components: {ToolBar},
  data() {
    return {
      currentPage: 1,
      total: 0,
      size: 12,
      tableData: [],
      dingUsersListName: null,
      finUserRosterList: [],
      userList: [],
      attendanceDate: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dialogFormVisible: false,
      getDataDialogFormVisible: false,
      form: {
        delete:false,
        start: null,
        end: null,
        userId: null,
        name: null,
        workDate: new Date().getTime() - 3600 * 1000 * 24,
        timeResult: null,
        checkType: null,
        checked: false,
        // 审批数据控制
        type: '',
        // 是否进行每日考勤计算
        isDayCalculate: true,
        userIds: []
      },
      formLabelWidth: '120px',
      timeResultList: [
        {
          label: "正常",
          value: "Normal",
        },
        {
          label: "早退",
          value: "Early",
        }, {
          label: "迟到",
          value: "Late",
        }, {
          label: "严重迟到",
          value: "SeriousLate",
        }, {
          label: "旷工迟到",
          value: "Absenteeism",
        }, {
          label: "未打卡",
          value: "NotSigned",
        },
      ],
      multipleSelection: []
    }
  },
  created() {
    this.attendanceDate[0] = this.$tools.getCurrWeekDays().start
    this.attendanceDate[1] = this.$tools.getCurrWeekDays().end
    this.getDataList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    tableRowClassName({row, rowIndex}) {
      console.log(row.basicattendance)
      if (row.basicattendance < 8) {
        return 'error-row';
      } else if (row.basicattendance === 8) {
        return 'success-row';
      }
      return '';
    },
    goGetData() {
      this.getDataDialogFormVisible = true
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.multipleSelection.push(row)
      this.deleteById()
    },
    getDataList() {
      this.dialogFormVisible = false
      this.form.start = this.attendanceDate[0]
      this.form.end = this.attendanceDate[1]
      console.log("查询数据：", this.form)
      axios.post("/ding_attendance_result/list/" + this.currentPage + "/" + this.size, this.form).then(res => {
        console.log("打卡信息：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1
        }

      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    goSearch() {
      this.dialogFormVisible = true
    },
    reSet() {
      this.form = {
        start: null,
        end: null,
        userId: null,
        name: null,
        workDate: null,
        timeResult: null,
        checkType: null,
      }
      this.getDataList()

    },
    handleChange() {
      // this.$store.commit("setUser", this.form.productline)
      this.getDataList()
    },
    handleUserChange() {
      // this.form.userId=
      console.log('Form:', this.form)
    },
    deleteById() {
      console.log("用户扫描删除")
      this.$tools.showMessageBox("确认删除选择的" + this.multipleSelection.length + "条数据？", "操作确认", "warning").then(confirm => {
        axios.post("/ding_attendance_result/deleteBatch/" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.multipleSelection).then(res => {
          this.$tools.showMessage(res.data.message, res.data.success ? 'success' : "error")
          if (res.data.success) {
            this.getDataList()
            this.multipleSelection = []
          }
        })
      }).catch(cancel => {
        this.$tools.showMessage("操作取消！", "info")
        this.multipleSelection = []
      })
    },
    updateById() {
      console.log("")
    },
    getDataFromDingDing() {
      this.form.start = moment(this.attendanceDate[0]).format("YYYY-MM-DD")
      this.form.end = moment(this.attendanceDate[1]).format("YYYY-MM-DD")
      if (this.form.checked) {
        this.form.type = 'LIAN_BAN_JIA_BAN';
      } else {
        this.form.type = '';
      }
      console.log("查询数据：", this.form)
      this.$tools.openLoading()
      axios.post("/ding_attendance_result/getFromDingDing", this.form).then(res => {
        if (res.data.success) {
          this.getDataDialogFormVisible = false
          this.getDataList()
          this.$tools.closeLoading()

        }
      })
    },
    getTheMonthData() {
      this.form.start = moment(this.attendanceDate[0]).format("YYYY-MM-DD")
      this.form.end = moment(this.attendanceDate[1]).format("YYYY-MM-DD")
      if (this.form.checked) {
        this.form.type = 'LIAN_BAN_JIA_BAN';
      } else {
        this.form.type = '';
      }
      console.log("查询数据：", this.form)
      this.$tools.openLoading()
      axios.post("/ding_attendance_result/getTheMonth", this.form).then(res => {
        if (res.data.success) {
          this.getDataDialogFormVisible = false
          this.getDataList()
          this.$tools.closeLoading()
        }
      })
    }
  }

}
</script>

<style scoped lang="less">
.scan_record {
  .select {
    //margin-bottom: 0.5rem;
    display: inline-flex !important;

    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
}

</style>
